package com.hyving.home.jpamulti.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Objects;


@Configuration  //定义主配置类，在启动时注入bean到spring容器中
@EnableTransactionManagement //开启生明式事务
@EnableJpaRepositories( //用来扫描指定的包及其子包中repository定义
        value="com.hyving.home.jpamulti.repository.second",
        entityManagerFactoryRef="secondEntityManagerFactory",
        transactionManagerRef="secondTransactionManager")//设置dao层（持久层，即repo）所在位置
public class SecondDataConfig {

    @Autowired
    @Qualifier("secondDataSource")
    private DataSource secondDataSource; //注入主配置类中的主数据源


    /**
     * 实体管理工厂的bean
     */
    @Bean(name = "secondEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory(EntityManagerFactoryBuilder builder) {

        return builder
                .dataSource(secondDataSource)
                //这个是指向你的domain, entity的路径。 实体类所在的包
                .packages("com.hyving.boot.dynamic.jpa.repository.second")
                .persistenceUnit("second")
                .build();
    }

    /**
     * 配置 实体管理器
     */
    @Bean(name = "secondEntityManager")
    public EntityManager secondEntityManager(EntityManagerFactoryBuilder builder){
        return  Objects.requireNonNull(secondEntityManagerFactory(builder).getObject()).createEntityManager();
    }


    /**
     * 配置事务管理
     */
    @Bean(name = "secondTransactionManager")
    public PlatformTransactionManager secondTransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(Objects.requireNonNull(secondEntityManagerFactory(builder).getObject()));
    }


}
